#include "settingpage.h"
#include <QDebug>
#include <QSettings>
#include <QStandardPaths>
#include <QMessageBox>
#include <QtCore/QCoreApplication>
#include <QErrorMessage>
#include "currentdeviceinfo.h"
#include "unistd.h"
#include "util/xatom-helper.h"
#include "mainwindow.h"
#include <QVBoxLayout>

bool SettingPage::press = false;
int SettingPage::dev_change = 1;
QSettings *SettingPage::resolution_setting = new QSettings(QCoreApplication::applicationDirPath() + "/.configure/kylin-camera/resolution_setting");
QGSettings *SettingPage::m_pGsettingThemeData;

SettingPage::SettingPage(QWidget *parent) : QWidget(parent)
{

#ifdef __V10__
    this->setStyleSheet( \
            "background: #1C1C1E;"
            "box-shadow: 0px 3px 16px rgba(0, 0, 0, 0.5);"
            "opacity: 1;");

#endif
    m_pGsettingThemeData = new QGSettings(FITTHEMEWINDOW);  //安装窗口
//    默认窗口配置
//    this->hide();
//    this->setWindowTitle(tr("setting"));
//    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
//    this->setWindowIcon(QIcon(":/image/camera-app"));     //lhl debug 更改设置页面图标
//    this->raise();

    init_ui();
    change_item();
    connect(m_pGsettingThemeData,&QGSettings::changed,this,&SettingPage::dealSystemGsettingChange); //lhl debug
}

SettingPage::~SettingPage(){
    settingPageTitle->deleteLater();
}

void SettingPage::Geometry(QPoint *pos){
    this->setGeometry(pos->x(),pos->y(),0,0);
    this->setFixedSize(400,400);
    //this->setFixedSize(460,454);
}

//设置ui
void SettingPage::init_ui(){

    //文字部分
    titleLab = new QLabel;            //标题
    dirlab = new QLabel;              //默认存储位置
    //browselab = new QLabel;         //浏览
    cameraDevicelab = new QLabel;     //默认摄像头
    savePhotoFormatlab = new QLabel;  //照片格式
    savevideoFormatlab = new QLabel;  //视频格式
    scalelab = new QLabel;            //拍摄分辨率

    //功能框部分
    dir = new QLineEdit(this);              //默认存储位置
    browse = new QPushButton(this);          //浏览
    cameraDevice = new QComboBox(this);      //默认摄像头
    savePhotoFormat = new QComboBox(this);  //照片格式
    savevideoFormat = new QComboBox(this);  //视频格式
    scale = new QComboBox(this);            //拍摄分辨率

    confirm = new QPushButton;
    cancel = new QPushButton;

    vlayout = new QVBoxLayout;   //整体页面
    dirLayout = new QHBoxLayout;
    titleLayout = new QHBoxLayout;
    cameraDeviceLayout = new QHBoxLayout;
    savePhotoFormatLayout = new QHBoxLayout;
    savevideoFormatLayout = new QHBoxLayout;
    scaleLayout = new QHBoxLayout;
    btnLayout = new QHBoxLayout;

    //功能框中显示
    current_dir_lab = new QLabel;
    current_cameraDev = new QLabel;
    current_savePhotoFormat = new QLabel;
    current_savevideoFormat = new QLabel;
    //current_scale = new QLabel;

    //翻译显示
    titleLab->setText(tr("camera setting")); //摄像头设置
    dirlab->setText(tr("The image path:")); //默认存储位置
    browse->setText(tr("browse"));//浏览
    cameraDevicelab->setText(tr("Camera device:"));//默认摄像头
    savePhotoFormatlab->setText(tr("save photo format:"));//照片格式
    savevideoFormatlab->setText(tr("save video format:"));//视频格式
    scalelab->setText(tr("The image scale:"));//拍摄分辨率
    confirm->setText(tr("confirm"));//确认
    cancel->setText(tr("cancel"));//取消

    //功能框部分尺寸设置
    dir->setFixedSize(170,32);
    cameraDevice->setFixedSize(245,32);
    savePhotoFormat->setFixedSize(245,32);
    savevideoFormat->setFixedSize(245,32);
    savePhotoFormat->addItem("jpg");
    savePhotoFormat->addItem("png");
    savePhotoFormat->addItem("bmp");

    savevideoFormat->addItem("mp4");
    savevideoFormat->addItem("avi");
    savevideoFormat->addItem("vfw");

    scale->setFixedSize(245,32);
    browse->setFixedSize(70,32);

    QString labStyle = \
        "font-size: 14px;"
        "line-height: 32px;"
        "opacity: 1;";
    QString titleLabStyle = \
        "font-size: 17px;"
        "line-height: 32px;"
        "opacity: 1;";

    titleLab->setStyleSheet(titleLabStyle);
    dirlab->setStyleSheet(labStyle);
    cameraDevicelab->setStyleSheet(labStyle);
    savePhotoFormatlab->setStyleSheet(labStyle);
    savevideoFormatlab->setStyleSheet(labStyle);
    scalelab->setStyleSheet(labStyle);

    QHBoxLayout *dirbtnLayout = new QHBoxLayout;
    dirbtnLayout->addWidget(current_dir_lab);
    dirbtnLayout->addStretch(10);
    dirbtnLayout->setMargin(0);
    dir->setLayout(dirbtnLayout);

    QHBoxLayout *photobtnLayout = new QHBoxLayout;
    photobtnLayout->addWidget(current_savePhotoFormat);
    photobtnLayout->addStretch(10);
    photobtnLayout->setMargin(0);
    savePhotoFormat->setLayout(photobtnLayout);

    QHBoxLayout *videobtnLayout = new QHBoxLayout;
    videobtnLayout->addWidget(current_savevideoFormat);
    videobtnLayout->addStretch(10);
    videobtnLayout->setMargin(0);
    savevideoFormat->setLayout(videobtnLayout);

    //标题栏水平布局
    titleLayout->addSpacing(13);
    titleLayout->addWidget(titleLab);
    titleLayout->setMargin(0);

    //默认存储位置水平布局
    dirLayoutWidget = new QWidget;
    dirLayout->addSpacing(20);
    dirLayout->addWidget(dirlab);
    dirLayout->addSpacing(3);
    dirLayout->addWidget(dir);
    dirLayout->addWidget(browse);
    dirLayout->addSpacing(20);
    dirLayout->setMargin(0);
    dirLayoutWidget->setLayout(dirLayout);

    //默认摄像头水平布局
    cameraDeviceLayoutWidget = new QWidget;
    cameraDeviceLayout->addSpacing(20);
    cameraDeviceLayout->addWidget(cameraDevicelab);
    cameraDeviceLayout->addSpacing(3);
    cameraDeviceLayout->addWidget(cameraDevice);
    cameraDeviceLayout->addSpacing(20);
    cameraDeviceLayout->setMargin(0);
    cameraDeviceLayoutWidget->setLayout(cameraDeviceLayout);

    //照片格式水平布局   
    savePhotoFormatLayoutWidget = new QWidget;
    savePhotoFormatLayout->addSpacing(20);
    savePhotoFormatLayout->addWidget(savePhotoFormatlab);
    savePhotoFormatLayout->addWidget(savePhotoFormat);
    savePhotoFormatLayout->addSpacing(20);
    savePhotoFormatLayout->setMargin(0);
    savePhotoFormatLayoutWidget->setLayout(savePhotoFormatLayout);


    //视频格式水平布局   
    savevideoFormatLayoutWidget = new QWidget;
    savevideoFormatLayout->addSpacing(20);
    savevideoFormatLayout->addWidget(savevideoFormatlab);
    savevideoFormatLayout->addWidget(savevideoFormat);
    savevideoFormatLayout->addSpacing(20);
    savevideoFormatLayout->setMargin(0);
    savevideoFormatLayoutWidget->setLayout(savevideoFormatLayout);


    //拍摄分辨率水平布局
    scaleLayoutWidget = new QWidget;
    scaleLayout->addSpacing(20);
    scaleLayout->addWidget(scalelab);
    scaleLayout->addWidget(scale);
    scaleLayout->addSpacing(20);
    scaleLayout->setMargin(0);
    scaleLayoutWidget->setLayout(scaleLayout);


    //确认取消布局
    btnLayout->addStretch(99);
    btnLayout->addWidget(cancel);
    btnLayout->addWidget(confirm);
    btnLayout->addSpacing(20);

    vlayout->addSpacing(25);
    vlayout->addLayout(titleLayout);
    vlayout->addWidget(dirLayoutWidget);
    vlayout->addWidget(cameraDeviceLayoutWidget);
    vlayout->addWidget(savePhotoFormatLayoutWidget);
    vlayout->addWidget(savevideoFormatLayoutWidget);
    vlayout->addWidget(scaleLayoutWidget);
    vlayout->addSpacing(16);
    vlayout->addLayout(btnLayout);
    vlayout->addSpacing(16);
    this->setLayout(vlayout);
    cameraDevice->setDuplicatesEnabled(false);

    //设置背景色白色
    nowThemeStyle = m_pGsettingThemeData->get("styleName").toString(); //lhl debug
    this->setGeometry(0,0,300,100);
    QPalette pal(this->palette());
    if (nowThemeStyle == "ukui-dark" || nowThemeStyle == "ukui-black"){
        //设置背景色黑色
        pal.setColor(QPalette::Background,Qt::black);
    }
    else{
        //设置背景色白色
        pal.setColor(QPalette::Background,Qt::white);
    }
    this->setAutoFillBackground(true);
    this->setPalette(pal);

    connect(browse,&QPushButton::clicked,this,&SettingPage::dir_click);
    connect(this,&SettingPage::change_dev,this,&SettingPage::change_cameraDevice);
    connect(confirm,&QPushButton::clicked,this,&SettingPage::confirm_click);
    connect(cancel,&QPushButton::clicked,this,&SettingPage::cancel_click);
    connect(cameraDevice,&QComboBox::currentTextChanged,this,[=](){
        scale->clear();
        QString devname =  camera_name2dev[cameraDevice->currentText()];
        char *in_device = devname.toLocal8Bit().data();
        V4l2DeviceInfo device_info;
        memset(&device_info,0X00,sizeof(V4l2DeviceInfo));
        memcpy(device_info.dev_path, in_device, strlen(in_device)+1);
        KylinCamera::enum_device(&device_info);

        for(TypePixFormats fmt : device_info.fmt_supported){
            if(fmt.frm_sizes_len){
                for(auto a: fmt.frm_sizes){

                    QPair<uint,uint> discrete;
                    discrete.first = a.frm_size.discrete.width;
                    discrete.second = a.frm_size.discrete.height;

                    if(discrete.first != 0 && discrete.second != 0){
                        QString str;
                        if(discrete.first == 0) continue;
                        str = QString::number(discrete.first) + "x" + QString::number(discrete.second);
                        scale->addItem(str);
                    }

                }
                break;
            }
        }
    });

}


void SettingPage::close(){
    this->window()->close();
}

//当设备有变化时更新设备列表，
//加入设备到device选项中
void SettingPage::change_item(){
    //添加摄像头设备
   //由于读取设备文件需要时间,这里开一个线程等待设备读取
    static int a = 1;
    bool need_change = 0;
    cameraDevice->clear();
    qDebug()<< "call time " << a++;
    *CameraPage::cameras = QCameraInfo::availableCameras();
    cameraDevice->setDuplicatesEnabled(1); // 功能按钮用户可以在组合框中输入重复项

    //将读到的设备加到设置列表中
    foreach(const QCameraInfo &cameraInfo,*CameraPage::cameras){

        QString device_name;
        device_name = cameraInfo.description() + cameraInfo.deviceName();

        camera_name2dev[device_name] = cameraInfo.deviceName();
        cameraDevice->addItem(device_name);
        //在设备列表中显示当前界面显示的摄像头
        if(device_name.contains(CurrentDeviceInfo::current_device_name)){
            cameraDevice->setCurrentText(device_name);
        }

    }
    CurrentDeviceInfo::current_device_name = cameraDevice->currentText();
    scale->clear();

    for(auto p : CurrentDeviceInfo::available_size){
        QString str;
        if(p.first == 0) continue;
        str = QString::number(p.first) + "x" + QString::number(p.second);
        qDebug () << str;
        scale->addItem(str);
    }
    CameraPage::cameras->clear();
}

//
void SettingPage::change_cameraDevice(const char *dev_name){
    Q_UNUSED(dev_name)
}


//设置存储路径
void SettingPage::dir_click(){
    current_dir = QFileDialog::getExistingDirectory(nullptr,tr("Select the directory"),"/home",
                                                    QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    first = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
    if(QDir(current_dir).exists() && current_dir != "" && current_dir.contains(first,Qt::CaseSensitive) /*|| current_dir.contains("/media/")*/){ //"/media为u盘所在目录"
        current_dir_lab->setText(current_dir);
        current_dir_lab->setToolTip(current_dir);
        return;
    }
    if(QDir(current_dir).exists() && current_dir != ""){
        QMessageBox::warning(this,tr("error"),tr("The directory does not have write permissions, select the user directory to store the files ."));
    }
}


void SettingPage::confirm_click(){
    //设置摄像头
    //SettingPage
    if(Button::video_start) {
        cancel_click();
        QMessageBox::warning(this,tr("waring"),tr("The settings cannot be changed during recording"));
        return;
    }

    //设置存储路径

    if(QDir(current_dir).exists() && current_dir != "" && (current_dir.contains(first,Qt::CaseSensitive) /*|| current_dir.contains("/media")*/)
            && current_dir != MainWindow::setting->get("save-path").toString()){
        current_dir.append('/');
        current_dir_lab->setText(current_dir);
        current_dir_lab->setToolTip(current_dir);
        emit dir_change(); //将路径储存到配置文件里
    }

    //切换设备
    if(CameraPage::has_device && CameraPage::current_indevice != camera_name2dev[cameraDevice->currentText()]){
        QString text = cameraDevice->currentText();
        QString str = camera_name2dev[text];
        CurrentDeviceInfo::current_device_name = cameraDevice->currentText();//更新当前摄像头名字
        qDebug() << text << " " << str;
        dev_change = 1;
        emit change_dev(str.toLocal8Bit().data());
    }

    //切换分辨率
    if(CameraPage::has_device && MainWindow::setting->get("scale-index").toInt()/*resolution_setting->value("scale").toInt()*/ != scale->currentIndex()){
        emit change_resolutions(CurrentDeviceInfo::available_size[scale->currentIndex()]); //获取分辨率
        //SettingPage
        MainWindow::setting->set("scale-index",scale->currentIndex());
        //完成预览页面转换
    }

    //选择存储图片格式
    if(CameraPage::has_device && MainWindow::setting->get("photo-format").toInt() != savePhotoFormat->currentIndex()){
        MainWindow::setting->set("photo-format",savePhotoFormat->currentIndex());

    }
    //选择视频存储格式
    if(CameraPage::has_device && MainWindow::setting->get("video-format").toInt() != savevideoFormat->currentIndex()){
        MainWindow::setting->set("video-format",savevideoFormat->currentIndex());
    }
    cancel_click();
}


void SettingPage::cancel_click(){
    this->window()->close();
}


void SettingPage::mousePressEvent(QMouseEvent *event){
    press = true;
    if(event->button() == Qt::LeftButton){
        m_start = event->globalPos();
    }
}


void SettingPage::mouseMoveEvent(QMouseEvent *event)
{
    if(!press) return;
    // 持续按住才做对应事件
//    if(pTitleBar->m_leftButtonPressed) {
//        将父窗体移动到父窗体原来的位置加上鼠标移动的位置：event->globalPos()-m_start
//        将鼠标在屏幕中的位置替换为新的位置
    this->move(event->globalPos() + this->geometry().topLeft() - m_start);
    m_start = event->globalPos();
//    }
}

void SettingPage::mouseReleaseEvent(QMouseEvent *event)
{
    // 鼠标左键释放
    if (event->button() == Qt::LeftButton) {
        // 记录鼠标状态
        press = false;
    }
}

//更新设备信息
void SettingPage::update(){
//    if(dev_change){
        scale->clear();
        for(auto p : CurrentDeviceInfo::available_size){
            QString str;
            if(p.first == 0) continue;
            str = QString::number(p.first) + "x" + QString::number(p.second);
            qDebug () << str;
            scale->addItem(str);
        }
        auto Size =  CurrentDeviceInfo::current_size;
        scale_str = QString::number(Size.first) + "x" + QString::number(Size.second);
        dev_change = 0;
//    }

    current_dir = MainWindow::setting->get("save-path").toString();
    current_dir_lab->setText(current_dir);
    current_dir_lab->setToolTip(current_dir);

    current_photoFormat = MainWindow::setting->get("photo-format").toInt();
    savePhotoFormat->setCurrentIndex(MainWindow::setting->get("photo-format").toInt());
    qDebug() << "savePhotoFormat" << MainWindow::setting->get("photo-format").toInt();

    current_videoFormat = MainWindow::setting->get("video-format").toInt();
    savevideoFormat->setCurrentIndex(MainWindow::setting->get("video-format").toInt());
    qDebug() << "savevideoFormat" << MainWindow::setting->get("video-format").toInt();

    //初始化当前设备
    if(!CurrentDeviceInfo::current_device_name.isEmpty())
        cameraDevice->setCurrentText(CurrentDeviceInfo::current_device_name);
        cameraDevice->setToolTip(cameraDevice->currentText());
        scale->setCurrentIndex(MainWindow::setting->get("scale-index").toInt());
}

//冗余代码 需优化
void SettingPage::dealSystemGsettingChange(const QString key){
    if(key == "styleName"){
        refreshThemeBySystemConf();
    }
}

void SettingPage::refreshThemeBySystemConf(){
    QString themeNow = m_pGsettingThemeData->get("styleName").toString();
    //this->setGeometry(0,0,300,100);
    QPalette pal(this->palette());
    //深色模式下
    if (themeNow == "ukui-dark" || themeNow == "ukui-black"){
        //设置背景色黑色
        pal.setColor(QPalette::Background,Qt::black);
    }
    else{
        //设置背景色白色
        pal.setColor(QPalette::Background,Qt::white);
    }
    this->setAutoFillBackground(true);
    this->setPalette(pal);
}

